import { useEffect, useReducer } from 'react';

const dataFetchReducer = (state, action) => {
    switch (action.type) {
        case 'FETCH_INIT':
            return {
                ...state,
                isLoading: true,
                isError: false
            };
        case 'FETCH_SUCCESS':
            return {
                ...state,
                isLoading: false,
                isError: false,
                total: action.payload.total || 0,
                data: action.payload.rows || []
            };
        case 'FETCH_FAILURE':
            return {
                ...state,
                isLoading: false,
                isError: true
            };
        default:
            throw new Error();
    }
};

const useDataApi = (fn, params, ...args) => {
    const [state, dispatch] = useReducer(dataFetchReducer, {
        isLoading: false,
        isError: false,
        total: 0,
        data: []
    });

    useEffect(() => {
        let didCancel = false;
        const fetchData = async () => {
            dispatch({ type: 'FETCH_INIT' });
            try {
                const result = await fn(params, ...args);
                const { data, code } = result;
                if (!didCancel) {
                    if (code === 10000) {
                        dispatch({ type: 'FETCH_SUCCESS', payload: data });
                    } else {
                        dispatch({ type: 'FETCH_FAILURE' });
                    }
                }
            } catch (error) {
                if (!didCancel) {
                    dispatch({ type: 'FETCH_FAILURE' });
                }
            }
        };
        fetchData();
        return () => {
            didCancel = true;
        };
    }, [params]);

    return [state.isLoading, state.data, state.total, state.isError];
};

export default useDataApi;
